<!--
 * @Description: 轮播
 * @Author: wang_k
 * @Date: 2023-08-15 15:44:55
 * @LastEditTime: 2025-04-24 11:31:08
 * @FilePath: /demo_important/src/components/listScroll.vue
-->
<template>
  <div
    class="listScroll"
    ref="box"
  >
    <slot></slot>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: "listScroll",
  created() { },
  mounted() {
    this.handlerInit()
  },  
  props: {
    // 步长
    speed: {
      default: 1,
      type: Number,
    },
  },
  computed: {
    //第一个slot
    ele0() {
      return this.$refs.box.childNodes[0];
    },
    //第二个slot
    ele1() {
      return this.$refs.box.childNodes[1];
    },
    //盒子的可视宽度
    boxWidth() {
      return this.$refs.box.clientWidth;
    },
  },
  data() {
    return {
      width: 0,
      isScroll: true,
    };
  },
  methods: {
    handlerInit() {
      //在盒子内容宽度小于可视宽度时不滚动
      console.log(this.boxWidth, this.ele0.clientWidth, this.$refs.box.childNodes[0]);
      if (this.boxWidth < this.ele0.clientWidth) {
        this.start(this.width);
        this.setEvet();
      } else {
        this.isScroll = false;
        this.ele1.style = "display:none"
      }
    },
    //鼠标移入停止滚动 移出继续滚动
    setEvet() {
      this.$refs.box.onmouseenter = () => {
        this.isScroll = false;
        // this.width = 0;
      };
      this.$refs.box.onmouseleave = () => {
        this.isScroll = true;
        this.$nextTick(() => {
          this.start(this.width);
        });
      };
    },
    //滚动方法
    start(width) {
      this.ele0.style = `transform:translateX(-${width}px);`;
      this.ele1.style = `transform:translateX(-${width}px);`;
      if (width >= this.ele0.clientWidth) {
        this.width = 0;
      } else {
        this.width += this.speed;
      }
      if (!this.isScroll) return;
      window.requestAnimationFrame(() => {
        this.start(this.width);
      });
    },
  },
};
</script>

<style scoped>
.listScroll {
  overflow: hidden;
}
.hover {
  overflow-x: auto;
}
.hide {
  display: none;
}
</style>